import json
import logging
import math
import os
import re
import time

import numpy
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

class login(object):
    user_agent = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    cookie = 你的cookie
    userid=你的ID
    user_agent_header = {
        'user_agent': user_agent,
        'cookie': cookie
    }

    def get_total_fan_count(self):
        url = f'https://api.bilibili.com/x/relation/followers?vmid={self.userid}&pn=1&ps=1&order=desc&order_type=attention&jsonp=jsonp&callback=__jp5'
        resp = requests.get(url, headers={
            'user_agent': self.user_agent,
            'cookie': self.cookie,
            'Referer': 'https://space.bilibili.com/527444290/fans/fans',
            'Host': 'api.bilibili.com'
        }, verify=False)
        match = re.search(r'__jp5\((.*)\)', resp.text)
        match_json = match.group(1).__str__()
        json_node = json.loads(match_json)
        total_count = json_node['data']['total']
        pages = int((total_count + 49) / 50)
        print(f'我的所有粉丝列表页数: {pages}')
        return pages

    def get_50_fans(self, index):
        url = f'https://api.bilibili.com/x/relation/followers?vmid=527444290&pn={index}&ps=50&order=desc&order_type=attention&jsonp=jsonp&callback=__jp5'
        fans_uids = {}
        try:
            resp = requests.get(url, headers={
                'user_agent': self.user_agent,
                'cookie': self.cookie,
                'Referer': 'https://space.bilibili.com/527444290/fans/fans',
                'Host': 'api.bilibili.com'
            }, verify=False)
            match = re.search(r'__jp5\((.*)\)', resp.text)
            match_json = match.group(1).__str__()
            json_nodes = json.loads(match_json)['data']['list']
            for node in json_nodes:
                uid = node['mid']
                uname = node['uname']
                fans_uids[uid] = uname
        except:
            print(f'获取粉丝列表失败：{index}')
        return fans_uids

    def get_total_up_page(self, uid):
        url = f'https://api.bilibili.com/x/relation/followings?vmid={uid}&pn=1&ps=1&order=desc&jsonp=jsonp&callback=__jp3'
        resp = requests.get(url, headers={
            'user_agent': self.user_agent,
            'cookie': self.cookie,
            'Referer': f'https://space.bilibili.com/{uid}/fans/follow',
            'Host': 'api.bilibili.com'
        }, verify=False)
        match = re.search(r'__jp3\((.*)\)', resp.text)
        match_json = match.group(1).__str__()
        json_node = json.loads(match_json)
        if ('code' in json_node) & (json_node['code'] == 22115):
            return 0
        total_count = json_node['data']['total']
        pages = int((total_count + 49) / 50)
        print(f'{uid} 关注的UP主列表页数: {pages}')
        return pages

    def get_50_ups(self, uid, index):
        url = f'https://api.bilibili.com/x/relation/followings?vmid={uid}&pn={index}&ps=50&order=desc&jsonp=jsonp&callback=__jp3'
        ups_uids = {}
        try:
            resp = requests.get(url, headers={
                'user_agent': self.user_agent,
                'cookie': self.cookie,
                'Referer': f'https://space.bilibili.com/{uid}/fans/follow',
                'Host': 'api.bilibili.com'
            }, verify=False)
            match = re.search(r'__jp3\((.*)\)', resp.text)
            match_json = match.group(1).__str__()
            json_nodes = json.loads(match_json)['data']['list']
            for node in json_nodes:
                uid = node['mid']
                uname = node['uname']
                ups_uids[uid] = uname
        except:
            print(f'{uid}获取关注列表失败：{index}')
        return ups_uids


list = []
fans_uids = []
log = login()
page_count = log.get_total_fan_count()
for index in range(1, page_count + 1):
    time.sleep(0.1)
    for item in log.get_50_fans(index).items():
        fans_uids.append(item)

temp=0
for item in fans_uids:
    # temp+=1
    # if temp==10:
    #     break
    time.sleep(0.1)
    # print(item)
    ups_uids = []
    item_uid = item[0]
    page_count = log.get_total_up_page(item_uid)
    if page_count == 0:
        print(f'用户设置隐私：{item}')
        continue
    for index in range(1, 6):
        time.sleep(0.1)
        for item1 in log.get_50_ups(item_uid, index).items():
            ups_uids.append(item1)
    for item2 in ups_uids:
        i = 0
        is_find=False
        for l1 in list:
            if l1['uid'] == item2[0]:
                list[i]['count'] += 1
                is_find=True
                break
            i += 1
        if is_find==False:
            list.append({'username': item2[1], 'uid': item2[0], 'count': 1})

for item in sorted(list, key=lambda l2: l2['count'], reverse=True):
    # print(item)
    if item['count']>10:
        with open(r'./record.txt', 'a') as f:
            try:
                f.write(f'{item}\n')
            except:
                print(f'写入异常：{item}')
# ups_uids = []
# page_count = log.get_total_up_page(393627187)
# for index in range(1, page_count + 1):
#     time.sleep(0.1)
#     for item in log.get_50_ups(393627187, index):
#         ups_uids.append(item)
# for item in ups_uids:
#     print(item)
